const jwt = require('jsonwebtoken');

const { JWT_SECRET } = require('@config/config.default');

const { userRegisterErr, userUpdatePwdErr } = require('@constant/error.type');

const { controller, emit } = require('@utils/tools');

const { userAdd, userGet, userUpdate } = require('./user.service');

module.exports = {
  async register(ctx) {
    const { user_name, password } = ctx.request.body;

    const params = { user_name, password };

    const res = await controller(params, userAdd);

    emit(ctx, res, { id: res.id, user_name: res.user_name }, userRegisterErr);
  },

  async login(ctx) {
    const { user_name } = ctx.request.body;

    const { password, ...userInfo } = await controller({ user_name }, userGet);

    const token = jwt.sign(userInfo, JWT_SECRET, { expiresIn: '1d' });

    emit(ctx, true, { token }, userRegisterErr);
  },

  async rePassword(ctx) {
    const params = {
      id: ctx.state.user.id,
      password: ctx.request.body.password,
    };

    const { status, id } = await controller(params, userUpdate);

    emit(ctx, status, { id }, userUpdatePwdErr);
  },
};
